import { Button, DatePicker } from 'antd';
import type { FormInstance } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import StatisticsCard from '@/components/StatisticsCard/Index';
import './style.less'
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { ProFormFieldSet } from '@ant-design/pro-form';
import { getSupplierSaleData, downSupplierSaleData } from '@/services/report/api'; 
import { subtractDays, currentDate, isNull, showMsg, isSupportSticky } from '@/utils/utils';
import moment from 'moment';
import PermissionControl from '@/components/PermissionControl';

const Index: React.FC = () => {
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [detail, setDetail] = useState({});
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '供应商名称',
      dataIndex: 'supplier',
      width: 130,
      fieldProps: {
        placeholder: '输入供应商名称',
      },
    },
    {
      title: '批次编号',
      dataIndex: 'batchId',
      width: 120,
      fieldProps: {
        placeholder: '输入批次编号',
      },
    },
    {
      title: '结算周期',
      dataIndex: 'rangedate',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet style={{gap: 2}}>
            <DatePicker allowClear={false} style={{width: '100%'}} />
              <span style={{padding: '0 5px'}}>-</span>
            <DatePicker allowClear={false} style={{width: '100%'}} />
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '商品编号',
      dataIndex: 'goodsId',
      width: 120,
      fieldProps: {
        placeholder: '完整商品编号',
      },
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 130,
      fieldProps: {
        placeholder: '拼音首字母/文字',
      },
    },
    {
      title: '商品规格',
      dataIndex: 'specsName',
      search: false,
      width: 130,
    },
    {
      title: '协议进货价',
      dataIndex: 'agreePrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '进货折扣',
      dataIndex: 'purchaseDiscount',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '实际进货价',
      dataIndex: 'purchasePrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '成交总量',
      dataIndex: 'sellNum',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '退款总量',
      dataIndex: 'refundNum',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '结算总量',
      dataIndex: 'realSellNum',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '结算金额',
      dataIndex: 'realTotalPrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    },
    
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 50,
      render: (_, record) => [
        <PermissionControl action_id="700703002"><a key="view" onClick={() => history.push({
          pathname: '/report/supplier-settle-statistics/detail',
          query: {
            id: record.goodsId as string,
            title: record.goodsName as string,
            supplier: record.supplier as string,
            batchId: record.batchId as string,
            start: searchParams.begin_date_str as string,
            end: searchParams.end_date_str as string,
          }
        })}>详情</a></PermissionControl>
      ]
    }
  ];

  useEffect(() => {
    formRef.current?.setFieldsValue({
      rangedate: [subtractDays(30), '-', currentDate()]
    });
    formRef.current?.submit();
  }, [])

  const getList = async(params: any) => {
    try {
      params.begin_date_str = moment(params.rangedate[0]).format('YYYYMMDD');
      params.end_date_str = moment(params.rangedate[2]).format('YYYYMMDD');
      const data = await getSupplierSaleData(params);
      setDetail(data);
      console.log('params', params)
      setSearchParams(params);
      return {
        data: data.record_list,
        success: true,
        total: data.sum_record_num
      }
    } catch (error) {
      showMsg(error?.data?.errmsg); 
      return {
        data: [],
        success: true,
        total: 0
      };
    }
  }


  const download = async() => {
    setLoading(true);
    await downSupplierSaleData(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }
  
  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<STOCKGOODSAPI.GoodsItem, STOCKGOODSAPI.GoodsItem & COMMON.PageParams>
        formRef={formRef}
        actionRef={actionRef}
        rowKey="goods_id"
        bordered
        className="custome-table"
        search={{
          defaultCollapsed: false,
          collapseRender: () => { return ''},
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              ...dom,
              <PermissionControl action_id="700703001">
                <Button key="export" type="primary" loading={loading} disabled={isNull(detail.record_list)} onClick={download}>导出报表</Button>
              </PermissionControl>
            ]
          }
        }}
        request={getList}
        options={false}
        columns={columns}
        scroll={{ x : 1280 }}
        tableExtraRender={(_, data) => (
          <div className='StatisticsCard' style={{ background: '#fff', padding: 12 }}>
            <div style={{marginBottom: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
              <StatisticsCard iconType="database" title="结算商品种类" number={detail.goods_type_num}/>
              <StatisticsCard title="结算总额" number={`￥${detail.real_sett_price}`}/>
              <StatisticsCard title="交易商品进货总额" number={`￥${detail.total_sett_price}`} />
              <StatisticsCard style={{marginRight: 0}} title="退款商品进货总额" number={`￥${detail.total_refund_price}`} />
            </div>
          </div>
        )}
      />
    </PageContainer>
  );
};
export default Index;
